package com.wechatpay.spring.boot.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import com.wechatpay.v3.sdk.WechatConfig;
import com.wechatpay.v3.sdk.WechatPay;

/**
 * @author liuyi <liuy@pvc123.com>
 * @since 2021/7/13
 */
@org.springframework.context.annotation.Configuration
@EnableConfigurationProperties(MondaWechatPayProperties.class)
public class MondaWechatPayAutoConfiguration {

    final Logger logger = LoggerFactory.getLogger(MondaWechatPayAutoConfiguration.class);

    private final MondaWechatPayProperties properties;

    public MondaWechatPayAutoConfiguration(MondaWechatPayProperties properties) {
        this.properties = properties;
    }

    @Bean("wechatPay")
    @ConditionalOnMissingBean
    public WechatPay wechatPay() {
        if(null != this.properties && null != this.properties.getMerchantId() && null != this.properties.getMerchantSerialNumber()){
            logger.info("Init wxpay, mchid:{}",this.properties.getMerchantId());
            WechatConfig wechatConfig = new WechatConfig(
                    this.properties.getAppId(),
                    this.properties.getMerchantId(),
                    this.properties.getKey(),
                    this.properties.getApiV3Key(),
                    this.properties.getCertFilePath(),
                    this.properties.getMerchantSerialNumber(),
                    this.properties.getNotifyOrderCallbackUrl(),
                    this.properties.getNotifyRefundCallbackUrl()
            );
            return new WechatPay(wechatConfig);
        }
        return null;
    }
}
